<template>
  <div class="product-edit">
    <el-card class="box-card">
      <div slot="header">
        <span>{{ isEdit ? '编辑商品' : '新增商品' }}</span>
      </div>
      
      <el-form 
        ref="productForm" 
        :model="productForm" 
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="productForm.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" placeholder="请选择商品分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input v-model="productForm.brand" placeholder="请输入品牌" />
        </el-form-item>

        <el-form-item label="售价格" prop="price">
          <el-input-number 
            v-model="productForm.price" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>

        <el-form-item label="采购价格" prop="purchasePrice">
          <el-input-number 
            v-model="productForm.purchasePrice" 
            :precision="2" 
            :step="0.1" 
            :min="0"
          />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <el-select v-model="productForm.supplierId" placeholder="请选择供应商">
            <el-option
              v-for="item in supplierOptions"
              :key="item.supplierId"
              :label="item.supplierName"
              :value="item.supplierId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="#"
            :http-request="handleUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <img v-if="imageDisplay" :src="imageDisplay" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            type="textarea"
            v-model="productForm.description"
            :rows="4"
            placeholder="请输入商品描述"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getProductDetail, updateProduct, addProduct } from '@/api/products'
import { getCategories } from '@/api/categories'
import { getSuppliers } from '@/api/suppliers'

export default {
  name: 'ProductEdit',
  data() {
    return {
      isEdit: false,
      productForm: {
        productId: null,
        productName: '',
        categoryId: '',
        brand: '',
        price: 0,
        purchasePrice: 0,
        description: '',
        imageUrl: '',
        supplierId: '',
      },
      imageUrl: '',
      categoryOptions: [],
      supplierOptions: [],
      rules: {
        productName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        brand: [
          { required: true, message: '请输入品牌', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入销售价格', trigger: 'blur' }
        ],
        purchasePrice: [
          { required: true, message: '请输入采购价格', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.getCategories()
    this.getSuppliers()
    const id = this.$route.params.id
    if (id) {
      this.isEdit = true
      this.getDetail(id)
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getProductDetail(id)
        if (res.code === 200) {
          const { 
            productId, productName, categoryId, brand, price, 
            purchasePrice, description, imageUrl, supplierId 
          } = res.data
          this.productForm = { 
            productId, productName, categoryId, brand, price, 
            purchasePrice, description, imageUrl, supplierId,
            imageFile: null
          }
          this.imageUrl = imageUrl
        }
      } catch (error) {
        console.error('获取商品详情失败:', error)
        this.$message.error('获取商品详情失败')
      }
    },
    async getCategories() {
      try {
        const res = await getCategories({
          pageNum: 1,
          pageSize: 1000
        })
        if (res.code === 200) {
          this.categoryOptions = res.data.list
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
      }
    },
    async getSuppliers() {
      try {
        const res = await getSuppliers({
          pageNum: 1,
          pageSize: 1000
        })
        if (res.code === 200) {
          this.supplierOptions = res.data.list
        }
      } catch (error) {
        console.error('获取供应商列表失败:', error)
        this.$message.error('获取供应商列表失败')
      }
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    handleUpload(options) {
      const file = options.file
      this.productForm.imageFile = file
      this.productForm.imageUrl = null
      this.imageUrl = URL.createObjectURL(file)
    },
    async submitForm() {
      try {
        await this.$refs.productForm.validate()
        
        const formData = new FormData()
        
        Object.keys(this.productForm).forEach(key => {
          if (this.productForm[key] !== null && key !== 'imageUrl') {
            formData.append(key, this.productForm[key])
          }
        })

        if (this.productForm.imageFile) {
          formData.append('imageFile', this.productForm.imageFile)
        } else if (this.productForm.imageUrl) {
          formData.append('imageUrl', this.productForm.imageUrl)
        }

        const res = this.isEdit 
          ? await updateProduct(formData)
          : await addProduct(formData)

        if (res.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '添加成功')
          this.goBack()
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }
    },
    goBack() {
      this.$router.push('/products')
    }
  },
  computed: {
    imageDisplay() {
      if (!this.imageUrl) return ''
      // 如果是完整的URL就直接使用
      if (this.imageUrl.startsWith('http')) {
        return this.imageUrl
      }
      // 否则拼接基础URL
      return process.env.VUE_APP_BASE_API + '/static/upload/' + this.imageUrl
    }
  },
  beforeDestroy() {
    // 清理本地预览URL
    if (this.imageUrl && this.imageUrl.startsWith('blob:')) {
      URL.revokeObjectURL(this.imageUrl)
    }
  }
}
</script>

<style lang="less" scoped>
.product-edit {
  padding: 20px;

  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;

    &:hover {
      border-color: #409EFF;
    }
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
